package com.multicampus.simplewiki.search;

import java.io.File;

import org.apache.lucene.analysis.cjk.CJKAnalyzer;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import com.multicampus.simplewiki.model.Document;

public class DocumentIndexer implements Indexer<Document> {
	private IndexWriter writer;
	private static Indexer<Document> indexer;

	public static Indexer<Document> getInstance() throws Exception {
		if (indexer == null) {
			indexer = new DocumentIndexer();
		}

		return indexer;
	}

	private DocumentIndexer() throws Exception {
		Directory directory;
		directory = FSDirectory.getDirectory(new File("/db/index"));

		writer = new IndexWriter(directory, new CJKAnalyzer(), true);
	}

	public void addIndex(Document document) throws Exception {
		org.apache.lucene.document.Document indexdocument = new org.apache.lucene.document.Document();
		indexdocument.add(new Field("content", document.getContent(), Field.Store.YES, Field.Index.TOKENIZED));
		indexdocument.add(new Field("id", String.valueOf(document.getId()), Field.Store.YES, Field.Index.UN_TOKENIZED));
		indexdocument.add(new Field("title", document.getTitle(), Field.Store.YES, Field.Index.TOKENIZED));
		indexdocument.add(new Field("tags", document.getTags(), Field.Store.YES, Field.Index.TOKENIZED));
		indexdocument.add(new Field("username", document.getAuthor().getName(), Field.Store.YES, Field.Index.TOKENIZED));

		writer.addDocument(indexdocument);
		writer.optimize();
	}
	
	public void deleteIndex(Document document) throws Exception{
		IndexReader reader = IndexReader.open("/db/index");
		reader.deleteDocuments(new Term("id", String.valueOf(document.getId())));
		reader.close();
	}
	
	public void updateIndex(Document document) throws Exception{
		deleteIndex(document);
		addIndex(document);
	}
}
